<!-- 科目余额表页面 -->
<template>
  <div class="padding" v-loading="loading">
    <el-card>
      <el-form
        :inline="true"
        :model="searchCriteria"
        ref="searchCriteria"
        size="mini"
        class="padding-top-sm flex justify-between"
      >
        <el-form-item prop="period" label="会计期间">
          <el-date-picker
            v-model="searchCriteria.period"
            type="monthrange"
            value-format="yyyy-MM"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item prop="financeSubjectNo" label="科目代码">
          <span @dblclick="financeSubjectTree('startFinanceSubjectNo')">
            <el-input
              v-model="searchCriteria.startFinanceSubjectNo"
              style="width:150px"
            />
          </span>
          <span class="margin-lr-sm">-</span>
          <span @dblclick="financeSubjectTree('endFinanceSubjectNo')">
            <el-input
              v-model="searchCriteria.endFinanceSubjectNo"
              style="width:150px"
            />
          </span>
        </el-form-item>

        <el-form-item prop="current" label="币种">
          <el-select v-model="searchCriteria.current" filterable clearable>
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="(item, value) in currencyMap"
              :key="value"
              :value="value"
              :label="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="level" label="科目级别">
          <!--<el-input v-model="searchCriteria.level" />-->
          <el-input-number
            v-model="searchCriteria.level"
            :min="1"
            :max="5"
            style="width:150px"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="warning" @click="exportTable">导出.xls</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
      <span v-show="isShow" style="color:#606266" class="text-xl"
        >请选择会计期间再进行查询</span
      >

      <el-divider></el-divider>

      <!-- :row-style="tableRowClassName" -->
      <el-table
        class="text-sm table-box"
        size="mini"
        style="width:100%"
        id="out-eltable"
        stripe
        :data="tableData"
        v-if="istableData"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column label="期间" prop="period"> </el-table-column>
        <el-table-column label="科目代码" prop="financeSubjectNo">
          <template slot-scope="scope">
            <div @dblclick="openDetail(scope)">
              {{ scope.row.financeSubjectNo }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="科目名称" prop="financeSubjectName">
        </el-table-column>
        <el-table-column label="币种" prop="currency"></el-table-column>
        <el-table-column label="期初余额" prop="initialBalanceDirection">
        </el-table-column>
        <el-table-column label="本期发生额">
          <el-table-column label="借方" prop="accrualDebit"></el-table-column>
          <el-table-column label="贷方" prop="accrualCredit"></el-table-column>
        </el-table-column>
        <el-table-column label="本年累计发生额">
          <el-table-column label="借方" prop="accumulativeYearAccrualDebit">
          </el-table-column>
          <el-table-column label="贷方" prop="accumulativeYearAccrualCredit">
          </el-table-column>
        </el-table-column>
        <el-table-column label="余额方向" prop="debitOrCreditor">
        </el-table-column>
        <el-table-column label="期末余额" prop="endTermBalanceDirection">
        </el-table-column>
      </el-table>
    </el-card>
    <!--科目弹窗事件-->
    <el-dialog title="请选择科目" :visible.sync="dialogVisible">
      <template>
        <el-tabs v-model="subjectTypeActive" type="card">
          <el-tab-pane
            v-for="(item, index) in subjectTypeMap"
            :key="index"
            :label="m(item)"
          >
            <el-tree
              :data="subjectTypeDataMapJson[index]"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "subjectBalancetable",
  data() {
    return {
      defaultProps: {
        children: "financeSubjectNodes",
        label: "label"
      },
      dialogVisible: false,
      istableData: false,
      loading: false,
      isShow: true,
      currencyMap: {},
      searchCriteria: {
        level: 1
      },
      subjectTypeMap: {},
      subjectTypeDataMapJson: {},
      subjectTypeActive: 0,
      clickSubjectNo: "",
      tableData: []
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    m(k) {
      return m(k);
    },
    // 跳转明细账
    openDetail(scope) {
      let financeSubjectNo = scope.row.financeSubjectNo;
      let period = scope.row.period;
      window.open(
        `#/blank/finance__voucherdetail__main?financeSubjectNo=${financeSubjectNo}&period=${period}`
      );
    },
    // 双击科目事件
    async financeSubjectTree(rowNum) {
      this.dialogVisible = true;
      this.clickSubjectNo = rowNum;
      ajax("queryFinanceSubject", {}).then(
        res => {
          this.subjectTypeMap = res.subjectTypeMap;
          for (const i in res.subjectTypeDataMapJson) {
            this.sortData(res.subjectTypeDataMapJson[i]);
          }
          this.subjectTypeDataMapJson = res.subjectTypeDataMapJson;
        },
        error => {
          console.log(error);
        }
      );
    },
    handleNodeClick(d, n, l) {
      if (d.financeSubjectNodes) {
        return;
      }
      this.dialogVisible = false;
      const label = d.label;
      const financeSubjectNo = d.label.split(" ")[0];
      if (financeSubjectNo) {
        if (this.clickSubjectNo === "startFinanceSubjectNo") {
          this.searchCriteria.startFinanceSubjectNo = financeSubjectNo;
        } else if (this.clickSubjectNo === "endFinanceSubjectNo") {
          this.searchCriteria.endFinanceSubjectNo = financeSubjectNo;
        }
      }
    },
    sortData(data) {
      for (const tmp of data) {
        tmp.label = tmp.financeSubject.no + " " + tmp.financeSubject.name;
        if (
          Object.prototype.toString.call(tmp.financeSubjectNodes) ===
          "[object Array]"
        ) {
          this.sortData(tmp.financeSubjectNodes);
        }
      }
      return data;
    },
    async init() {
      let res = await ajax("init", {});
      if (!res) {
        this.$message.error("初始化页面信息失败，请刷新重试");
        return;
      }
      this.currencyMap = res.currencyMap;
    },
    // tableRowClassName({ row, index }) {
    //   if (
    //     row.currency !== "综合本位币" &&
    //     this.searchCriteria.current === "综合本位币"
    //   ) {
    //     let rowStyle = { display: "none" };
    //     return rowStyle;
    //   }
    // },
    query() {
      if (!this.searchCriteria.period) {
        this.$message.error("请选择会计期间再进行查询!");
        return;
      }
      this.isShow = false;
      this.istableData = true;
      this.loading = true;
      this.tableData = [];
      const startPeriod = this.searchCriteria.period[0];
      const endPeriod = this.searchCriteria.period[1];
      const startFinanceSubjectNo = this.searchCriteria.startFinanceSubjectNo;
      const endFinanceSubjectNo = this.searchCriteria.startFinanceSubjectNo;
      let current = this.searchCriteria.current;
      const level = this.searchCriteria.level;
      const star = parseInt(startPeriod.split("-"));
      const end = parseInt(endPeriod.split("-"));
      if (end - star >= 1) {
        this.$message.error("不允许跨年查询!");
      } else {
        ajax("query", {
          startPeriod,
          endPeriod,
          startFinanceSubjectNo,
          endFinanceSubjectNo,
          current,
          level
        }).then(
          res => {
            console.log(res);
            if (res.success) {
              for (let i of res.balanceSheets) {
                if (current === "综合本位币") {
                  i.accountBalanceSheetDatas = i.accountBalanceSheetDatas.filter(
                    x => x.currency === current
                  );
                  for (let k of i.accountBalanceSheetDatas) {
                    this.tableData.push({
                      period: i.period,
                      financeSubjectNo: i.financeSubjectNo,
                      financeSubjectName: i.financeSubjectName,
                      currency: k.currency,
                      initialBalanceDirection: k.initialBalanceDirection,
                      accrualDebit: k.accrualDebit,
                      accrualCredit: k.accrualCredit,
                      accumulativeYearAccrualDebit:
                        k.accumulativeYearAccrualDebit,
                      accumulativeYearAccrualCredit:
                        k.accumulativeYearAccrualCredit,
                      debitOrCreditor: i.debitOrCreditor,
                      endTermBalanceDirection: k.endTermBalanceDirection
                    });
                  }
                } else {
                  for (let k of i.accountBalanceSheetDatas) {
                    this.tableData.push({
                      period: i.period,
                      financeSubjectNo: i.financeSubjectNo,
                      financeSubjectName: i.financeSubjectName,
                      currency: k.currency,
                      initialBalanceDirection: k.initialBalanceDirection,
                      accrualDebit: k.accrualDebit,
                      accrualCredit: k.accrualCredit,
                      accumulativeYearAccrualDebit:
                        k.accumulativeYearAccrualDebit,
                      accumulativeYearAccrualCredit:
                        k.accumulativeYearAccrualCredit,
                      debitOrCreditor: i.debitOrCreditor,
                      endTermBalanceDirection: k.endTermBalanceDirection
                    });
                  }
                }
              }
            } else {
              this.$message.error(m(res.message));
            }
            for (let i of this.tableData) {
              i.debitOrCreditor = m(
                res.subjectBalanceTypeSelect[i.debitOrCreditor]
              );
            }
            console.log("this.tableData: ", this.tableData);
            this.loading = false;
          },
          error => {
            console.log(error);
          }
        );
      }
    },
    // 导出
    exportTable() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "科目余额表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  }
};
</script>
<style scoped>
/deep/ .table-box.el-table thead.is-group th {
  padding: 2px 0;
  background-color: white;
  text-align: center;
}
/deep/ .cell {
  width: 100%;
}
</style>
